package com.patrick.open.api.core.utils;

import org.apache.commons.lang.Validate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author patrick
 * @date 2020/5/31 4:36 下午
 * @Des spring上下文容器, 避免冗余初始化容器，存储在对象中，方便取出。
 * 最簡單的事是堅持，最難的事還是堅持
 */
public class SpringContextHolder implements ApplicationContextAware {
  private static ApplicationContext context;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext)
    throws BeansException {
    SpringContextHolder.context = applicationContext;
  }

  //获得applicationContext
  public static ApplicationContext getApplicationContext() {
    assertContextInjected();
    return context;
  }

  public static void clearHolder() {
    context = null;
  }

  //获取Bean
  public static <T> T getBean(Class<T> requiredType) {
    assertContextInjected();
    return (T) getApplicationContext().getBean(requiredType);
  }

  @SuppressWarnings("unchecked")
  public static <T> T getBean(String name) {
    assertContextInjected();
    return (T) getApplicationContext().getBean(name);
  }

  //判断application是否为空
  public static void assertContextInjected() {
    Validate.isTrue(context == null, "application未注入 ，请在springContext.xml中注入SpringHolder!");
  }

}
